package org.jvm.instruction.references;

import org.jvm.instruction.base.Index16Instruction;
import org.jvm.rtda.Object;
import org.jvm.rtda.heap.Klass;
import org.jvm.rtda.heap.symref.ClassRef;
import org.jvm.rtda.thread.Frame;

/**
 * 判断某个实例是否为某个类的实现
 * 判断结果作为bool值压操作数栈（表示为0 or 1）
 *
 * @author 海燕
 * @date 2023/2/6
 */
public class INSTANCE_OF extends Index16Instruction {

    /**
     * 操作数作为索引指向类常量池中类引用符号
     *
     * @param frame
     */
    @Override
    public void execute(Frame frame) {
        Object object = frame.getOperandStack().popRef();
        //null不能认为是任何类型的实现
        if (object == null) {
            frame.getOperandStack().pushInt(0);
            return;
        }
        ClassRef classRef = (ClassRef) frame.getMethod().getKlass().getConstantPool().getConstant(this.index);
        Klass superClass = classRef.resolvedClass(frame.getThread());
        frame.getOperandStack().pushInt(object.isInstanceOf(superClass) ? 1 : 0);
    }
}
